//
//  RCMainViewController.m
//  RCSideMenu
//
//  Created by razeen on 1/18/16.
//  Copyright © 2016 Razeen. All rights reserved.
//

#import "RCMainViewController.h"
#import "RCSideMenuViewController.h"
#import "RCNavigationViewController.h"

static const CGFloat viewSlideHorizonRatio = 0.55;
static const CGFloat viewHeightNarrowRatio = 0.80;
static const CGFloat menuStartNarrowRatio  = 0.70;

@interface RCMainViewController ()<UIGestureRecognizerDelegate>

@property (assign, nonatomic) CGFloat distance;         // 距离左边的边距
@property (assign, nonatomic) CGFloat leftDistance;
@property (assign, nonatomic) CGFloat menuCenterXStart; // menu起始中点的X
@property (assign, nonatomic) CGFloat menuCenterXEnd;   // menu缩放结束中点的X
@property (assign, nonatomic) CGFloat panStartX;        // 拖动开始的x值

@property (strong, nonatomic) RCBaseViewController *homeVC;
@property (strong, nonatomic) RCSideMenuViewController *menuVC;
@property (strong, nonatomic) RCNavigationViewController *navi;
@property (strong, nonatomic) UIView                 *cover;

@property (strong, nonatomic) UIPanGestureRecognizer* panMenuGesture;

@end

@implementation RCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.menuState = kMainVCMenuStateHome;
    self.distance = 0;
    self.menuCenterXStart = kScreenWIDTH * menuStartNarrowRatio / 2.0;
    self.menuCenterXEnd = self.view.center.x;
    self.leftDistance = kScreenWIDTH * viewSlideHorizonRatio;
    
    self.view.backgroundColor = UIColorFromRGB(0xdbdbdb, 1);
    
    self.menuVC = [[RCSideMenuViewController alloc]init];
//    WEAKSELF
    self.menuVC.selectMenuItemBlock = ^(NSNumber* selectedMenuItemNum)
    {
    };
    
    CGRect menuFrame = [[UIScreen mainScreen] bounds];
    menuFrame.size.width = 0.72 * kScreenWIDTH;
    self.menuVC.view.frame = menuFrame;
    
    self.menuVC.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, menuStartNarrowRatio, menuStartNarrowRatio);
    self.menuVC.view.center = CGPointMake(self.menuCenterXStart - (1 - viewSlideHorizonRatio)/2*kScreenWIDTH, self.menuVC.view.center.y);
    [self.view addSubview:self.menuVC.view];
    
    // 设置遮盖
    self.cover = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.cover.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.cover];
    
    self.homeVC = [self getHomeVC];
    // 设置控制器的状态，添加手势操作
    self.navi = [[RCNavigationViewController alloc] initWithRootViewController:self.homeVC];
    self.navi.navigationBar.barTintColor = [UIColor colorWithRed:0 green:122.0 / 255 blue:1.0 alpha:1.0];
    self.navi.navigationBar.tintColor = [UIColor whiteColor];
    [self.navi.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, nil]];
    
    [self addChildViewController:self.navi];
    [self.view addSubview:self.navi.view];
    self.panMenuGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    self.panMenuGesture.delegate = self;
    [self.navi.view addGestureRecognizer:self.panMenuGesture];
    
    
    // Do any additional setup after loading the view.
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 加阴影的代替方案， 右滑左边也会有阴影。
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        CGFloat shadowWidth = kSCALE(10);
        UIImageView* topImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -shadowWidth, kScreenWIDTH, shadowWidth)];
        UIImageView* leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-shadowWidth, -shadowWidth, shadowWidth, kScreenHEIGHT + shadowWidth*2)];
        UIImageView* bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.navi.view.frame.size.height, kScreenWIDTH, shadowWidth)];
        
        topImageView.image = [UIImage imageNamed:@"shadow_top"];
        leftImageView.image = [UIImage imageNamed:@"shadow_left"];
        bottomImageView.image = [UIImage imageNamed:@"shadow_bottom"];
        
        [self.navi.view addSubview:topImageView];
        [self.navi.view addSubview:leftImageView];
        [self.navi.view addSubview:bottomImageView];
    });
}



- (RCBaseViewController*) getHomeVC
{
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    RCBaseViewController *homeVC =  (RCBaseViewController*)[storyboard instantiateViewControllerWithIdentifier:@"RCMessageViewController"];

    homeVC.hasLeftMenuBtn = YES;
   
    return homeVC;
}

/**
 *  获取左上角显示左菜单的按钮控件
 */
- (UIButton*)leftNaviMenuBtn
{
    if ([self.navi.topViewController isKindOfClass:[RCBaseViewController class]])
    {
        return ((RCBaseViewController*)self.navi.topViewController).leftMenuBtn;
    }
    return nil;
}



/**
 *  设置statusbar的状态
 */
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

/**
 *  处理拖动事件
 *
 *  @param recognizer
 */
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    //    if (self.navi.viewControllers.count > 1) {
    //        return;
    //    }
    //    if ([self.navi.topViewController isKindOfClass:[TDBaseViewController class]]) {
    //          if(!((TDBaseViewController*)self.navi.topViewController).hasLeftMenuBtn)
    //              return;
    //    }
    // 当滑动水平X大于75时禁止滑动
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.panStartX = [recognizer locationInView:self.view].x;
    }
    if (self.menuState == kMainVCMenuStateHome && self.panStartX >= 75) {
        return;
    }
    
    CGFloat x = [recognizer translationInView:self.view].x;
    // 禁止在主界面的时候向左滑动
    if (self.menuState == kMainVCMenuStateHome && x < 0) {
        return;
    }
    
    CGFloat dis = self.distance + x;
    // 当手势停止时执行操作
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        if (dis >= kScreenWIDTH * viewSlideHorizonRatio / 2.0) {
            [self showMenuWhatever];
        } else {
            [self showHomeWhatever];
        }
        return;
    }
    
    CGFloat proportion = (viewHeightNarrowRatio - 1) * dis / self.leftDistance + 1;
    if (proportion < viewHeightNarrowRatio || proportion > 1) {
        return;
    }
    self.navi.view.center = CGPointMake(self.view.center.x + dis, self.view.center.y);
    self.navi.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, proportion, proportion);
    
    //    [self leftNaviMenuBtn].alpha = self.cover.alpha = 1 - dis / self.leftDistance;
    self.cover.alpha = 1 - dis / self.leftDistance;
    CGFloat menuProportion = dis * (1 - menuStartNarrowRatio) / self.leftDistance + menuStartNarrowRatio;
    CGFloat menuCenterMove = dis * (self.menuCenterXEnd - self.menuCenterXStart) / self.leftDistance;
    self.menuVC.view.center = CGPointMake(self.menuCenterXStart + menuCenterMove  - (1 - viewSlideHorizonRatio)/2*kScreenWIDTH, self.view.center.y);
    self.menuVC.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, menuProportion, menuProportion);
}

//- (void)setSta:(state)sta
//{
//    _sta = sta;
//    if (_sta == kStateHome) {
//        self.tapGes.cancelsTouchesInView = NO;
//    }
//    else
//    {
//        self.tapGes.cancelsTouchesInView = YES;
//    }
//}

/**
 *  展示侧边栏
 */
- (void)showMenu {
    if (self.menuState == kMainVCMenuStateMenu) {
        return;
    }
    self.distance = self.leftDistance;
    self.menuState = kMainVCMenuStateMenu;
    [self doSlide:viewHeightNarrowRatio];
}
/**
 *  展示侧边栏
 */
- (void) showMenuWhatever
{
    self.distance = self.leftDistance;
    self.menuState = kMainVCMenuStateMenu;
    [self doSlide:viewHeightNarrowRatio];
}

/**
 *  展示主界面
 */
- (void)showHome {
    if (self.menuState == kMainVCMenuStateHome) {
        return;
    }
    self.distance = 0;
    self.menuState = kMainVCMenuStateHome;
    [self doSlide:1];
}
/**
 *  展示主界面
 */
- (void) showHomeWhatever
{
    self.distance = 0;
    self.menuState = kMainVCMenuStateHome;
    [self doSlide:1];
}

- (void)pushVC:(UIViewController*)viewController animation:(BOOL)animatiaon
{
    [self.navi pushViewController:viewController animated:animatiaon];
}

/**
 *  实施自动滑动
 *
 *  @param proportion 滑动比例
 */
- (void)doSlide:(CGFloat)proportion {
    [UIView animateWithDuration:0.3 animations:^{
        self.navi.view.center = CGPointMake(self.view.center.x + self.distance, self.view.center.y);
        self.navi.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, proportion, proportion);
        
        //        [self leftNaviMenuBtn].alpha = self.cover.alpha = proportion == 1 ? 1 : 0;
        self.cover.alpha = proportion == 1 ? 1 : 0;
        CGFloat menuCenterX;
        CGFloat menuProportion;
        if (proportion == 1) {
            menuCenterX = self.menuCenterXStart;
            menuProportion = menuStartNarrowRatio;
        } else {
            menuCenterX = self.menuCenterXEnd;
            menuProportion = 1;
        }
        self.menuVC.view.center = CGPointMake(menuCenterX - (1 - viewSlideHorizonRatio)/2*kScreenWIDTH, self.view.center.y);
        self.menuVC.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, menuProportion, menuProportion);
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - UIGestureDelegate
/**
 如果navi中有许多的vc则左划手势不可用
 如果navi中栈顶vc没有做菜单的按钮则左划手势不可用
 */
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer == self.panMenuGesture) {
        if (self.navi.viewControllers.count > 1) {
            return NO;
        }
        if ([self.navi.topViewController isKindOfClass:[RCBaseViewController class]]) {
            if(!((RCBaseViewController*)self.navi.topViewController).hasLeftMenuBtn)
                return NO;
        }
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return self.menuState == kMainVCMenuStateHome;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
